Inside static methods it is forbiden to use instance variables. Static methods are shared with all instances of an class therefore we cannot talk about handling of separate instances.
There is tough some kind of variables that you can use inside those functions, you guess it: static variables.
Same story over and over again:
Because static member functions are not attached to a particular object, they can be called directly by using the class name and the scope operator. Like static member variables, they can also be called through objects of the class type, though this is not recommended.
Static member functions have two interesting quirks worth noting. First, because static member functions are not attached to an object, they have no this pointer! This makes sense when you think about it — the this pointer always points to the object that the member function is working on. Static member functions do not work on an object, so the this pointer is not needed.
Second, static member functions can only access static member variables. They can not access non-static member variables. This is because non-static member variables must belong to a class object, and static member functions have no class object to work with!
Here’s another example using static member variables and functions:
class IDGenerator
{
private:
static int s_nNextID;
public:
static int GetNextID() { return s_nNextID++; }
};
// We'll start generating IDs at 1
int IDGenerator::s_nNextID = 1;
int main()
{
for (int i=0; i < 5; i++)
cout << "The next ID is: " << IDGenerator::GetNextID() << endl;
return 0;
}
This program prints:
The next ID is: 1
The next ID is: 2
The next ID is: 3
The next ID is: 4
The next ID is: 5